<template>
  <view class='productList'>

    <view style="padding: 30rpx">
      <view class="infoCard">
        <uv-form labelPosition="left" :model="formData" :labelWidth="80" :rules="rules" ref="form">
          <uv-form-item label="头像" prop="studentIdPhotoFront" borderBottom>
            <template v-slot:right>
              <UvUpload :dataList="formData.avatar?[formData.avatar]:[]"
                        :params="{name:'avatar'}"
                        :upload_max="1" @uploadChange="uploadSuccess"/>
            </template>

          </uv-form-item>


          <uv-form-item label="昵称" prop="nickName" borderBottom>
            <template v-slot:right>
              <uv-input inputAlign="right" v-model="formData.nickName" border="none">
              </uv-input>
            </template>
          </uv-form-item>


          <uv-form-item label="性别" prop="sex" borderBottom>
            <template v-slot:right>
              <uv-radio-group :activeColor="themConfig.theme.color" iconColor="white" v-model="formData.sex">
                <uv-radio
                    :customStyle="{margin: '8px'}"
                    v-for="(item, index) in [{name:'男',value:'1'},{name:'女',value:'2'},{name:'未设置',value:'0'}]"
                    :key="index"
                    :label="item.name"
                    :name="item.value">
                </uv-radio>
              </uv-radio-group>
            </template>
          </uv-form-item>

          <uv-form-item @click="switchSchoolTab" label="学校" prop="schoolName" required borderBottom>
            <uv-input inputAlign="right" disabled="" placeholder="选择学校" v-model="formData.schoolName" border="none">
            </uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>

          <uv-form-item label="手机号" prop="phone" required borderBottom>
            <template v-slot:right>
              <uv-input inputAlign="right" placeholder="如实填写，接单人联系" v-model="formData.phone" border="none">
              </uv-input>
            </template>
          </uv-form-item>

        </uv-form>
      </view>

      <view class="agreement" v-if="isRegister">

        <view>
          <uv-checkbox-group v-model="isReadAggreement">
            <uv-checkbox
                :activeColor="themConfig.theme.subColor"
                :customStyle="{marginBottom: '3px'}"
                v-for="(item, index) in [{name:'',value: 1}]"
                :key="index" :label="item.name"
                :name="item.value"
            >已阅读同意
            </uv-checkbox>
          </uv-checkbox-group>
        </view>
        <view class="agreementText" :style="{
                    color:themConfig.theme.subColor
                  }">
          <text @click="readAgreement('50001')">《用户协议》
          </text>
          <text style="margin: 0 10rpx">和</text>
          <text :style="{
                    color:themConfig.theme.subColor
                  }" @click="readAgreement('50000')">《隐私政策》
          </text>
        </view>
      </view>

      <view style="width: 100%;margin-top: 20px">
        <uv-button @click="submit" text="提交"
                   :color="btnColor()"></uv-button>
      </view>
    </view>
    <uv-toast ref="toast"></uv-toast>
  </view>
</template>
<script>
import StatusNav from '@/components/school/statusNav';
import PageBody from '@/components/school/pageBody';
import {mapGetters} from "vuex";
import {toLogin} from '@/libs/login.js';
import diyJson from '@/config/diy.js';
import * as MemberApi from '@/api/member/user.js';
import UvUpload from '@/components/school/uv-upload';

const app = getApp();

export default {
  computed: mapGetters(['isLogin', 'userInfo']),
  components: {
    StatusNav,
    PageBody,
    UvUpload,
  },
  data() {
    return {
      themConfig: diyJson.commonStyle,
      formData: {},
      isReadAggreement: [0],
      isRegister: true,
      rules: {
        'nickName': {
          type: 'string',
          required: true,
          message: '请填昵称',
          trigger: ['blur', 'change']
        },
        'avatar': {
          type: 'string',
          required: true,
          message: '请上传头像',
          trigger: ['blur', 'change']
        },
        'schoolId': {
          type: 'string',
          required: true,
          message: '请选择学校',
          trigger: ['blur', 'change']
        },
      },
    };
  },

  onPullDownRefresh() {

  },
  onLoad: function (options) {

    if (!this.isLogin) {
      toLogin();
    }
    this.listenerSchool();

  },

  onShow() {

  },

  created() {
    this.getUserInfo();
  },

  methods: {
    listenerSchool() {
      let that = this;
      uni.$on('setSchool', (school) => {
        that.setSchool(school)
      });
    },

    // 切换学校
    switchSchoolTab() {
      uni.navigateTo({
        url: '/pages/school/info/index'
      })
    },
    setSchool(school) {
      this.formData['schoolId'] = school.id
      this.formData['schoolName'] = school.schoolName
    },

    readAgreement(code) {
      uni.navigateTo({
        url: `/pages/users/privacy/index?params=${encodeURIComponent(JSON.stringify({code: code}))}`
      })
    },

    getUserInfo() {
      // 刷新用户信息
      MemberApi.getUserInfo().then(res => {
        let data = res.data;
        console.log("data.phone", data.phone || false)
        this.isRegister = (data.phone === null || data.phone === '');

        let form = {};
        form.id = data.id;
        form.avatar = data.avatar;
        form.phone = data.phone;
        form.nickName = data.nickName;
        form.sex = data.sex;
        form.schoolName = data.schoolInfo !== null ? data.schoolInfo.schoolName : '';
        form.schoolId = data.schoolInfo !== null ? data.schoolInfo.schoolId : '';
        this.formData = form;

        this.$store.commit("UPDATE_USERINFO", data);
      })
      //
      // this.formData.id = this.userInfo.id;
      // this.formData.avatar = this.userInfo.avatar;
      // this.formData.phone = this.userInfo.phone;
      // this.formData.nickName = this.userInfo.nickName;
      // this.formData.sex = this.userInfo.sex;
    },

    // 获取支付渠道
    dataList() {

    },

    // 上传图片
    uploadSuccess(obj) {
      console.log("上传回调", obj)
      let name = obj.params.name;
      let array = obj.images;
      let photos = [];
      for (let i = 0; i < array.length; i++) {
        photos.push(array[i].url);
      }
      this.$nextTick(() => {
        this.formData[name] = photos.length > 0 ? photos[0] : null;
      });
      console.log("上传成功", this.formData)
    },

    goBack(url) {
      // #ifdef H5
      return history.back();
      // #endif
      // #ifndef H5
      return uni.navigateBack({
        delta: 1,
      })
      // #endif
    },

    btnColor() {
      return 'linear-gradient(to right,' + this.themConfig.theme.subColor + ',' + this.themConfig.theme.color + ')'
      // return' linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))';
    },

    submit() {

      if (this.isRegister && this.isReadAggreement[0] !== 1) {
        uni.showToast({
          icon: 'error',
          title: '请阅读用户协议和隐私条款'
        })
        return;
      }

      MemberApi.updateUser({...this.formData}).then(res => {
        this.getUserInfo();
        uni.showToast({
          icon: 'success',
          title: '保存成功，即将返回...'
        });
        uni.removeStorageSync("diyPageInfo");
        setTimeout(() => {
          this.goBack();
        }, 1000)

        // this.$refs.toast.show({
        //   ...params,
        //   complete() {
        //     that.goBack();
        //   }
        // })
      })
    },

    getApp() {
      return app;
    },

  },
  onReachBottom() {
  }
}
</script>

<style scoped lang="scss">
.infoCard {
  background-color: white;
  padding: 10px 30px;
  border-radius: 10px;
}

.payBtn {
  padding: 0 15px;
  display: flex;
  width: 100%;
}

.agreement {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  align-items: center;

  .agreementText {
    margin-top: -3px
  }
}
</style>
